package com.lujianfei.powersearch.utils

import android.content.ContentResolver
import android.content.ContentValues
import android.graphics.*
import android.media.MediaScannerConnection
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.util.LruCache
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import java.io.File
import java.io.OutputStream


/**
 * Author: mac
 * Date: 1.2.23 6:22 下午
 * Email:johnson@miaoshitech.com
 * Description:
 */
object SnapshotUtils {

    /**
     * 保存到相册
     * @param fileName String
     * @param bitmap Bitmap
     */
    fun saveBitmap2Gallery(fileName: String, bitmap: Bitmap) :String?{
        //图片保存的路径
        var mPicPath: String? = null
        val mPicDir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "snapShotPhotos")
        var out: OutputStream? = null
        var pathArray: Array<String>? = null
        var typeArray: Array<String>? = null
        try {
            // Android 10版本 创建文件夹不成功mPicPath
            val isMk: Boolean = mPicDir.mkdirs()
            Log.d("ImageUtils ", "isMk = $isMk")
            val mPicFile = File(mPicDir, "$fileName.jpg")
            mPicPath = mPicFile.absolutePath
            Log.d("ImageUtils ", "mPicPath = $mPicPath")
            pathArray = arrayOf(mPicFile.absolutePath)
            typeArray = arrayOf("image/jpeg")
            val values = ContentValues()
            val resolver: ContentResolver = SystemUtils.getApplicationContext().contentResolver
            values.put(MediaStore.Images.ImageColumns.DATA, mPicPath)
            values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, fileName)
            values.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/jpeg")
            values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, System.currentTimeMillis().toString() + "")
            // 插入相册
            val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
            if (uri != null) {
                out = resolver.openOutputStream(uri)
                out?.let {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)
                }
            }
        } catch (e: Exception) {
            mPicPath = null
            e.printStackTrace()
        } finally {
            if (out != null) {
                try {
                    out.flush()
                    out.close()
                    Log.d("ImageUtils", "finally close")
                    // 扫描刷新
                    MediaScannerConnection.scanFile(SystemUtils.getApplicationContext(), pathArray, typeArray) { s, uri -> Log.d("ImageUtils", "onScanCompleted  s->$s") }
                } catch (e: Exception) {
                    e.printStackTrace()
                    mPicPath = null
                }
            }
        }
        return mPicPath;
    }

    /**
     * View已经在界面上展示了，可以直接获取View的缓存
     * 对View进行量测，布局后生成View的缓存
     * View为固定大小的View，包括TextView,ImageView,LinearLayout,FrameLayout,RelativeLayout等
     * @param view 截取的View,View必须有固定的大小，不然drawingCache返回null
     * @return 生成的Bitmap
     */
    fun captureView(view: View): Bitmap {
        view.isDrawingCacheEnabled = true
        view.buildDrawingCache()
        // 重新测量一遍View的宽高
        view.measure(
            View.MeasureSpec.makeMeasureSpec(view.width, View.MeasureSpec.EXACTLY),
            View.MeasureSpec.makeMeasureSpec(view.height, View.MeasureSpec.EXACTLY)
        )
        // 确定View的位置
        view.layout(
            view.x.toInt(), view.y.toInt(), view.x.toInt() + view.measuredWidth,
            view.y.toInt() + view.measuredHeight
        )
        // 生成View宽高一样的Bitmap
        val bitmap = Bitmap.createBitmap(
            view.drawingCache, 0, 0, view.measuredWidth,
            view.measuredHeight
        )
        view.isDrawingCacheEnabled = false
        view.destroyDrawingCache()
        return bitmap
    }

    fun getRecyclerViewScreenshot(view: RecyclerView): Bitmap? {
        val adapter = view.adapter
        var bigBitmap: Bitmap? = null
        if (adapter != null) {
            val size = adapter.itemCount
            var height = 0
            val paint = Paint()
            var iHeight = 0f
            val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt()
            // Use 1/8th of the available memory for this memory cache.
            val cacheSize = maxMemory / 8
            val bitmaCache: LruCache<String, Bitmap> = LruCache(cacheSize)
            for (i in 0 until size) {
                val holder = adapter.createViewHolder(view, adapter.getItemViewType(i))
                adapter.onBindViewHolder(holder, i)
                holder.itemView.measure(
                    View.MeasureSpec.makeMeasureSpec(view.width, View.MeasureSpec.EXACTLY),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
                )
                holder.itemView.layout(
                    0,
                    0,
                    holder.itemView.measuredWidth,
                    holder.itemView.measuredHeight
                )
                holder.itemView.isDrawingCacheEnabled = true
                holder.itemView.buildDrawingCache()
                val drawingCache = holder.itemView.drawingCache
                if (drawingCache != null) {
                    bitmaCache.put(i.toString(), drawingCache)
                }
                height += holder.itemView.measuredHeight
            }
            bigBitmap = Bitmap.createBitmap(view.measuredWidth, height, Bitmap.Config.ARGB_8888)
            val bigCanvas = Canvas(bigBitmap)
            bigCanvas.drawColor(Color.WHITE)
            for (i in 0 until size) {
                val bitmap: Bitmap = bitmaCache.get(i.toString())
                bigCanvas.drawBitmap(bitmap, 0f, iHeight, paint)
                iHeight += bitmap.height
                bitmap.recycle()
            }
        }
        return bigBitmap
    }

    /**
     * 加入底图合成
     */
    fun synthesizeWithBg(frontBitmap:Bitmap, bgBitmap:Bitmap) {
        val canvas = Canvas(frontBitmap)
        // 叠加逻辑
        val paint = Paint()
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OVER)

        // 底图大小调整
        val scale = frontBitmap.width / bgBitmap.width.toFloat()
        val matrix = Matrix()
        matrix.postScale(scale, scale)
        val finalBgBitmap = Bitmap.createBitmap(bgBitmap,0,0,bgBitmap.width, bgBitmap.height, matrix, true)
        // 开始合成
        canvas.drawBitmap(finalBgBitmap, 0f,0f, paint)
    }
}